package work.fram;

import work.config.Constant;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class AutoSqlWriter {

    public static final AutoSqlWriter INSTANCE = new AutoSqlWriter();

    private Map<String, FileWriter> fileWriterMap = new HashMap<>();

    private AutoSqlWriter () {

    }

    public void write(String file, String sql) {
        FileWriter writer = fileWriterMap.get(file);
        if (writer == null) {
            File sqlFile = new File(Constant.work, "sql");
            if (!sqlFile.exists()) {
                sqlFile.mkdirs();
            }
            try {
                writer = new FileWriter(new File(sqlFile, file + ".sql"));
            } catch (IOException e) {
                e.printStackTrace();
            }

            fileWriterMap.put(file, writer);

        }

        try {
            writer.write(sql);
            writer.write("\n");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void close() {
        for (FileWriter value : fileWriterMap.values()) {
            try {
                value.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
